import React from 'react';
import { Table, Tag, Button, Popconfirm, Space, Typography, Tooltip } from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  MinusCircleOutlined,
  EyeOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
import type { ScanTaskInfo, PageResult } from '../../types';
import { STATUS_COLORS, TRIGGER_TYPE_LABELS } from '../../types';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

const { Text, Link } = Typography;

interface ScanTaskTableProps {
  data: PageResult<ScanTaskInfo>;
  loading?: boolean;
  onViewDetail: (task: ScanTaskInfo) => void;
  onDelete: (unitTaskId: number) => void;
  onPageChange: (page: number, pageSize: number) => void;
}

const ScanTaskTable: React.FC<ScanTaskTableProps> = ({
  data,
  loading = false,
  onViewDetail,
  onDelete,
  onPageChange
}) => {

  // 获取状态图标和颜色
  const getStatusConfig = (status: string) => {
    switch (status) {
      case 'SUCCESS':
        return { icon: <CheckCircleOutlined />, color: 'success', text: '成功' };
      case 'FAILED':
        return { icon: <CloseCircleOutlined />, color: 'error', text: '失败' };
      case 'RUNNING':
        return { icon: <SyncOutlined spin />, color: 'processing', text: '运行中' };
      case 'SKIPPED':
        return { icon: <MinusCircleOutlined />, color: 'default', text: '跳过' };
      default:
        return { icon: <MinusCircleOutlined />, color: 'default', text: status };
    }
  };

  // 计算耗时
  const calculateDuration = (startTime: string, endTime?: string) => {
    if (!endTime) return '-';

    const start = dayjs(startTime);
    const end = dayjs(endTime);
    const duration = end.diff(start, 'second');

    if (duration < 60) return `${duration}秒`;
    if (duration < 3600) return `${Math.floor(duration / 60)}分${duration % 60}秒`;

    const hours = Math.floor(duration / 3600);
    const minutes = Math.floor((duration % 3600) / 60);
    const seconds = duration % 60;
    return `${hours}时${minutes}分${seconds}秒`;
  };

  // 任务类型映射
  const taskTypeMap = [
    { key: 'JAR', field: 'jarTask', label: 'JAR', color: 'purple' },
    { key: 'GIT', field: 'gitTask', label: 'Git', color: 'green' },
    { key: 'APM', field: 'apmTask', label: 'APM', color: 'orange' },
    { key: 'SA', field: 'saTask', label: 'SA', color: 'blue' },
    { key: 'JACG', field: 'jacgTask', label: 'JACG', color: 'geekblue' },
    { key: 'STATISTICS', field: 'statisticsTask', label: '统计', color: 'cyan' }
  ];

  // 获取任务类型标签（根据任务开关）
  const getTaskTypeTags = (task: ScanTaskInfo) => {
    const enabledTasks = taskTypeMap.filter(type => (task as any)[type.field]);

    // 判断是否为全量执行：所有主要任务都启用
    const isFullScan = enabledTasks.length === taskTypeMap.length;

    if (isFullScan) {
      // 全量执行，显示"全量"标签
      return [{ key: 'FULL', label: '全量', color: 'gold' }];
    } else {
      // 部分任务执行，显示具体的任务类型
      return enabledTasks.map(type => ({ ...type }));
    }
  };

  const columns = [
    {
      title: '扫描任务ID',
      dataIndex: 'unitTaskId',
      key: 'unitTaskId',
      width: 120,
      render: (unitTaskId: number, record: ScanTaskInfo) => (
        <Link
          onClick={() => onViewDetail(record)}
          style={{ fontWeight: 'bold' }}
        >
          #{unitTaskId}
        </Link>
      )
    },
    {
      title: '触发方式',
      dataIndex: 'triggerType',
      key: 'triggerType',
      width: 100,
      render: (triggerType: string) => {
        const colorMap: { [key: string]: string } = {
          'MANUAL': 'blue',
          'SCHEDULE': 'green',
          'ARTIFACTORY': 'orange',
          'RETRY': 'purple'
        };

        return (
          <Tag color={colorMap[triggerType] || 'default'}>
            {TRIGGER_TYPE_LABELS[triggerType as keyof typeof TRIGGER_TYPE_LABELS] || triggerType}
          </Tag>
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = getStatusConfig(status);
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.text}
          </Tag>
        );
      }
    },
    {
      title: 'Git分支',
      dataIndex: 'gitBranch',
      key: 'gitBranch',
      width: 120,
      render: (branch?: string) => branch ? (
        <Tag color="default">{branch}</Tag>
      ) : '-'
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 160,
      render: (time: string) => (
        <Tooltip title={dayjs(time).fromNow()}>
          <Text type="secondary">
            {dayjs(time).format('MM-DD HH:mm')}
          </Text>
        </Tooltip>
      )
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 160,
      render: (time?: string) => time ? (
        <Tooltip title={dayjs(time).fromNow()}>
          <Text type="secondary">
            {dayjs(time).format('MM-DD HH:mm')}
          </Text>
        </Tooltip>
      ) : '-'
    },
    {
      title: '耗时',
      key: 'duration',
      width: 100,
      render: (_: any, record: ScanTaskInfo) => (
        <Text style={{ fontSize: '12px' }}>
          {calculateDuration(record.startTime, record.endTime)}
        </Text>
      )
    },
    {
      title: '任务类型',
      key: 'taskTypes',
      width: 180,
      render: (_: any, record: ScanTaskInfo) => {
        const tasks = getTaskTypeTags(record);
        return (
          <div>
            {tasks.map((task, index) => (
              <Tag key={task.key} color={task.color} style={{ margin: '2px', fontSize: '12px' }}>
                {task.label}
              </Tag>
            ))}
          </div>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right' as const,
      render: (_: any, record: ScanTaskInfo) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onViewDetail(record)}
          >
            详情
          </Button>
          <Popconfirm
            title="确定删除此扫描任务吗？"
            onConfirm={() => onDelete(record.unitTaskId)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <Table
      columns={columns}
      dataSource={data.records}
      loading={loading}
      rowKey="unitTaskId"
      scroll={{ x: 1200 }}
      pagination={{
        current: data.current,
        total: data.total,
        pageSize: data.size,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) =>
          `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        onChange: onPageChange,
        onShowSizeChange: onPageChange,
      }}
    />
  );
};

export default ScanTaskTable;